import axios from 'axios'
import type { AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import { Message } from '@arco-design/web-vue'
import { getToken } from '@renderer/utils/auth'
import useUserStore from '@renderer/store/modules/user'
import router from '@renderer/router'

export interface HttpResponse<T = unknown> {
  status: number
  msg: string
  code: string
  data: T
}
if (import.meta.env.RENDERER_VITE_BASE_URL) {
  axios.defaults.baseURL = import.meta.env.RENDERER_VITE_BASE_URL
} else {
  axios.defaults.baseURL = 'http://47.122.115.90:8000/admin-api'
}

axios.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // let each request carry token
    // this example using the JWT token`
    // Authorization is a custom headers key
    // please modify it according to the actual situation
    const userInfo = useUserStore()
    let token = getToken()
    if (!token) {
      token = 'test1'
    }
    config.headers['tenant-id'] = userInfo.tenantId || userInfo.localUserInfo?.tenantId
    config.headers.token = token
    return config
  },
  (error) => {
    // do something
    return Promise.reject(error)
  }
)
// add response interceptors
axios.interceptors.response.use(
  (response: AxiosResponse<HttpResponse, any>) => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== '20000') {
      if (res.code === '401') {
        const currentRoute = router.currentRoute.value
        router.push({
          name: 'login',
          query: {
            ...router.currentRoute.value.query,
            redirect: currentRoute.name as string
          }
        })
      } else {
        Message.error({
          content: res.msg || 'Error'
        })
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    }
    return res
  },
  (error) => {
    Message.error({
      content: error.msg || 'Request Error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
